package com.mzx.javase.thread.callable;

import java.util.Random;
import java.util.concurrent.*;

/**
 * 类描述：多线程的第三种方式，实现Callable接口
 *
 * @ClassName CallableTest
 * @Description TODO
 * @Author 马子鑫
 * @Date 2022/8/7 19:48
 * @Version 1.0
 */
public class CallableTest {
    public static void main(String[] args) {
        //实现了Callable的线程，必须借助使用Executor的方法去执行
        ExecutorService pool = Executors.newFixedThreadPool(3);
        MyCallable myCallable1 = new MyCallable("线程1");
        MyCallable myCallable2 = new MyCallable("线程2");
        MyCallable myCallable3 = new MyCallable("线程3");
        Future<Integer> future1 = pool.submit(myCallable1);
        Future<Integer> future2 = pool.submit(myCallable2);
        Future<Integer> future3= pool.submit(myCallable3);

        try {
            System.out.println("线程1结果为：" + future1.get());
            System.out.println("线程2结果为：" + future2.get());
            System.out.println("线程3结果为：" + future3.get());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}

/**
 * Callable是一个接口，可以传递泛型，代表返回值
 */
class MyCallable implements Callable<Integer> {

    private String name;

    public MyCallable(String name) {
        this.name = name;
    }

    @Override
    public Integer call() {
        System.out.println(name + "开始运算");
        int random = (int) (Math.random() * 10);
        System.out.println(name + "随机数为: " + random);
        int sum = 0;
        for (int i = 0; i <= random; i++) {
            sum += i;
        }
        return sum;
    }
}
